package com.btjava.maven.pomver.handler;

import com.btjava.maven.pomver.utils.NoticUtils;
import com.btjava.maven.pomver.utils.XmlParseUtils;
import com.intellij.openapi.ui.MessageType;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class SettingXmlHandler {
    /**
     * 从maven配置文件获取maven仓库地址
     */
    public static List<String> getMavenRepositoryUrl(String filePath){
        List<Element> elementList = XmlParseUtils.getElementByNamePath(filePath,"mirrors>mirror>url");
        if(Objects.isNull(elementList) || elementList.isEmpty()){
            return new ArrayList<>();
        }
        List<String> urlList = elementList.stream().filter(one->Objects.nonNull(one)
                && StringUtils.isNotBlank(one.getTextTrim())).map(one->parseUrl(one.getTextTrim())).collect(Collectors.toList());
        return urlList;
    }

    public static String parseUrl(String urlStr){
        String domian ="";
        try {
            URL url = new URL(urlStr);
            domian = url.getProtocol() +"://"+url.getHost()+"/";
        }catch (Exception e){
            NoticUtils.sendNotice("无效的maven仓库地址！:"+urlStr+"。",MessageType.ERROR);
        }
        return domian;
    }
}
